/*
 * Copyright 2003-2005 (c) Live Media Pty Ltd. <argot@einet.com.au> 
 *
 * This software is licensed under the Argot Public License 
 * which may be found in the file LICENSE distributed 
 * with this software.
 *
 * More information about this license can be found at
 * http://www.einet.com.au/License
 * 
 * The Developer of this software is Live Media Pty Ltd,
 * PO Box 4591, Melbourne 3001, Australia.  The license is subject 
 * to the law of Victoria, Australia, and subject to exclusive 
 * jurisdiction of the Victorian courts.
 */

using System;

using TypeElement = argot.TypeElement;
using TypeException = argot.TypeException;
using TypeInputStream = argot.TypeInputStream;
using TypeOutputStream = argot.TypeOutputStream;
using TypeReader = argot.TypeReader;
using TypeWriter = argot.TypeWriter;

namespace argot.common
{
	
	/// <summary> 
	/// This represents an unsigned 8bit byte.
	/// </summary>
	public class BigEndianUnsignedByte 
	:TypeReader, TypeWriter
	{
		
		public static System.String TYPENAME = "u8";
		
		public virtual System.Object Read(TypeInputStream inStream, TypeElement element)
		{
			int i;
			
			i = inStream.Stream.ReadByte();
			
			if (i == - 1)
				throw new System.IO.EndOfStreamException();
			
			return (System.Byte) i;
		}
		
		public virtual void Write(TypeOutputStream outStream, System.Object o, TypeElement element)
		{
			if (o is System.Int32)
			{
				int b = ((System.Int32) o);
				if (b < 0 || b > MAX)
					throw new TypeException("U8 out of range: " + b);
				
				outStream.Stream.WriteByte((System.Byte) b);
			}
			else if (o is System.Int16)
			{
				int b = (int) ((System.Int16) o);
				if (b < 0 || b > MAX)
					throw new TypeException("U8 out of range: " + b);
				
				outStream.Stream.WriteByte((System.Byte) b);
			}
			else if (o is System.Byte)
			{
				int b = (int) ((System.Byte) o);
				if (b < MIN || b > MAX)
					throw new TypeException("U8 out of range: " + b);
				
				outStream.Stream.WriteByte((System.Byte) b);
			}
			else
			{
				throw new TypeException("Not Recognized type passed to u8");
			}
		}
		
		public static int MIN = 0;
		public static int MAX = 256 - 1;
	}
}